package com.yeqian.attachment.config;


import com.yeqian.attachment.service.AttachmentService;
import com.yeqian.attachment.service.impl.FastDFSAttachmentServiceImpl;
import com.yeqian.attachment.service.impl.LocalAttachmentServiceImpl;
import com.yeqian.attachment.configuration.AttachmentConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.sql.Driver;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class FileUploadConfig {

    @Autowired
    private AttachmentConfigProperties attachmentConfigProperties;

    public FileUploadConfig() {
    }

    /**
     * @ConditionalOnClass 某个class位于类路径上，才会实例化一个Bean
     * @ConditionalOnMissingBean 仅仅在当前上下文中不存在某个对象时，才会实例化一个Bean
     * @return
     */
    @Bean
    @ConditionalOnClass({Driver.class})
    @ConditionalOnMissingBean({AttachmentService.class})
    @Conditional({FileCondition.LocalTypeCondition.class})
    public AttachmentService localFileManagerService() {
        log.info("本地文件存储");
        return new LocalAttachmentServiceImpl();
    }

    @Bean
    @ConditionalOnClass({Driver.class})
    @ConditionalOnMissingBean({AttachmentService.class})
    @Conditional({FileCondition.FASTDFSTypeCondition.class})
    public AttachmentService FastDFSFileManageService() {
        log.info("FASTDFS存储");
        return new FastDFSAttachmentServiceImpl();
    }

    public Set<String> getAllowFileExt() {
        String typeWhitelist = this.attachmentConfigProperties.getTypeWhitelist();
        if (StringUtils.isEmpty(typeWhitelist)) {
            return new HashSet<>();
        } else if (typeWhitelist.contains(",")) {
            String[] split = typeWhitelist.split(",");
            return (Set) Arrays.stream(split).map((s) -> s.trim().toLowerCase()).collect(Collectors.toSet());
        } else {
            return new HashSet<>(Collections.singletonList(typeWhitelist));
        }
    }

}
